package com.ruoyi.system.service.impl;

import java.util.List;
import java.util.Date;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.EpmInformationHistory;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.EpmInformationMapper;
import com.ruoyi.system.domain.EpmInformation;

/**
 * 员工信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-10
 */
@Service
public class EpmInformationServiceImpl implements IEpmInformationService 
{

    @Autowired
    private EpmInformationMapper epmInformationMapper;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private IEpmInformationService epmInformationService;

    @Autowired
    private IEpmInformationHistoryService epmInformationHistoryService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IEpmBlacklistService epmBlacklistService;

    /**
     * 查询员工信息
     * 
     * @param id 员工信息主键
     * @return 员工信息
     */
    @Override
    public EpmInformation selectEpmInformationById(Long id)
    {
        return epmInformationMapper.selectEpmInformationById(id);
    }

    /**
     * 查询员工信息列表
     * 
     * @param epmInformation 员工信息
     * @return 员工信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<EpmInformation> selectEpmInformationList(EpmInformation epmInformation)
    {


        return epmInformationMapper.selectEpmInformationList(epmInformation);
    }

    /**
     * 查询员工信息列表(定时任务用)
     *
     * @param epmInformation 员工信息
     * @return 员工信息
     */
    @Override
    public List<EpmInformation> selectEpmInformationListbyquart(EpmInformation epmInformation)
    {
        return epmInformationMapper.selectEpmInformationList(epmInformation);
    }

    /**
     * 新增员工信息
     * 
     * @param epmInformation 员工信息
     * @return 结果
     */
    @Override
    public int insertEpmInformation(EpmInformation epmInformation)
    {
        return epmInformationMapper.insertEpmInformation(epmInformation);
    }

    /**
     * 修改员工信息
     * 
     * @param epmInformation 员工信息
     * @return 结果
     */
    @Override
    public int updateEpmInformation(EpmInformation epmInformation)
    {
        //检验修改情况并计入日志
        epmInformationHistoryService.check_change(epmInformation);
        //修改SysUser表的对应信息
        SysUser sysUser = new SysUser();
        sysUser.setUserId(epmInformation.getUserId());
        // 修改员工性别 sex
        sysUser.setSex(epmInformation.getSex());
        //修改员工用户名称 nick-name
        sysUser.setNickName(epmInformation.getName());
        //修改员工手机号 phone-number
        sysUser.setPhonenumber(epmInformation.getPhoneNumber());
        sysUser.setDeptId(epmInformation.getDeptId());
        sysUser.setPostIds(epmInformation.getPostIds());
        sysUser.setRoleIds(epmInformation.getRoleIds());
        iSysUserService.updateUser(sysUser);

        return epmInformationMapper.updateEpmInformation(epmInformation);
    }

    /**
     * 批量删除员工信息
     * 
     * @param ids 需要删除的员工信息主键
     * @return 结果
     */
    @Override
    public int deleteEpmInformationByIds(Long[] ids)
    {
        return epmInformationMapper.deleteEpmInformationByIds(ids);
    }

    /**
     * 删除员工信息信息
     * 
     * @param id 员工信息主键
     * @return 结果
     */
    @Override
    public int deleteEpmInformationById(Long id)
    {
        return epmInformationMapper.deleteEpmInformationById(id);
    }

    /**
     * 删除员工信息信息
     *
     * @param UserId 员工信息主键
     * @return 结果
     */
    @Override
    public int Record_onboarding_status(Long UserId){
        return epmInformationMapper.Record_onboarding_status(UserId);
    }


    /**
     * 进行员工注册前信息检验
     *
     * @param epmInformation 员工信息主键
     * @return 结果int（0表示员工在系统中有记录，但是已经离职，1表示检查通过）
     */
    @Override
    public int check_epm_add(EpmInformation epmInformation){
        if (epmInformation == null || epmInformation.getName() == null || epmInformation.getName().isEmpty() ||
                epmInformation.getIdCard() == null || epmInformation.getIdCard().isEmpty()) {
            throw new ServiceException("新增员工失败，姓名与身份证号不能为空");
        }

       if(epmBlacklistService.checkIdCard(epmInformation.getIdCard())){
           throw new ServiceException("新增员工'" + epmInformation.getName() + "'失败，当前员工处于黑名单中");
       }
        EpmInformation info = epmInformationMapper.checkIdCardUnique(epmInformation.getIdCard());
       //查看是否有记录
        if (StringUtils.isNotNull(info) )
        {
              if (info.getEmployed_or_not()==1){
                  throw new ServiceException("新增员工'" + epmInformation.getName() + "'失败，当前员工已在职");
              } else if (info.getEmployed_or_not()==0){
               //该返回表示员工在系统中有记录，但是已经离职
                return 0;
            }
        }
      //该返回表示检查通过
        return 1;
    }

    /**
     * 入职员工功能
     *
     * @param epmInformation,getUsername 员工信息主键,修改人
     * @return 结果
     */
    @Override
    public int add_epm(EpmInformation epmInformation,String getUsername){

        //进行登陆前校验
        if(epmInformationService.check_epm_add(epmInformation)==0){
            //进行数据补全
            epmInformation=add_epm_info_Completion(epmInformation);
            //进行老员工重新入职
            return epmInformationService.insert_old_EpmInformation(epmInformation);
        }
        //进行数据补全
        epmInformation=add_epm_info_Completion(epmInformation);
        //赋值并创建账号
        SysUser sysUser = new SysUser();
        sysUser.setNickName(epmInformation.getName());
        sysUser.setUserName(epmInformation.getIdCard());
        sysUser.setCreateBy(getUsername);
        sysUser.setDeptId(epmInformation.getDeptId());
        sysUser.setPassword(SecurityUtils.encryptPassword(configService.selectConfigByKey("sys.user.initPassword")));
        sysUser.setRoleIds(epmInformation.getRoleIds());
        sysUser.setPostIds(epmInformation.getPostIds());
        //验证账号是否重复
        if (!iSysUserService.checkUserNameUnique(sysUser))
        {
            throw new ServiceException("新增用户'" + sysUser.getNickName() + "'失败，该身份证号注册的账号已存在");
        }
        //注册用户账号
        iSysUserService.insertUser(sysUser);
       //获取刚刚注册的用户的账号id
        List<SysUser> list = iSysUserService.selectUserList(sysUser);
        if (!list.isEmpty()) {
            SysUser firstUser = list.get(0);
            epmInformation.setUserId(firstUser.getUserId());
        } else {
            throw new ServiceException("注册账号成功但是系统检索不到账号");

        }
        //将新增员工信息记录日志
        EpmInformationHistory epmInformationHistory=new EpmInformationHistory();
        //将epmInformation复制到epmInformationHistory
        BeanUtils.copyProperties(epmInformation,epmInformationHistory);
        epmInformationHistory.setUpdateBy(getUsername);
        epmInformationHistoryService.insertEpmInformationHistory(epmInformationHistory,1);

        //在入职或离职状态表创建信息
        epmInformationService.Record_onboarding_status(epmInformation.getUserId());
        return epmInformationService.insertEpmInformation(epmInformation);
    }



    /**
     * 老员工重新入职
     *
     * @param epmInformation 员工信息
     * @return 结果
     */
    @Override
    public int insert_old_EpmInformation(EpmInformation epmInformation)
    {
        //获取Userid信息
        epmInformation.setUserId(epmInformationMapper.selectEpmInformationByIdcard(epmInformation.getIdCard()).getUserId());

        //将重新入职员工信息记录日志
        EpmInformationHistory epmInformationHistory=new EpmInformationHistory();

        //将epmInformation复制到epmInformationHistory
        BeanUtils.copyProperties(epmInformation,epmInformationHistory);
        epmInformationHistoryService.insertEpmInformationHistory(epmInformationHistory,1);

       //启动账号
        userMapper.start_UserStatus(epmInformation.getUserId());

        //更新基本信息
        epmInformationService.updateEpmInformation(epmInformation);

        //修改是否在职信息表信息
       return  epmInformationMapper.add_old_epm(epmInformation.getIdCard());


    }



    /**
     * 导入用户数据
     *
     * @param epmList 用户数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importepm(List<EpmInformation> epmList, String operName) {


        if (StringUtils.isNull(epmList) || epmList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (EpmInformation epm : epmList)
        {
            try {

                epmInformationService.add_epm(epm, operName);
                successNum++;
                successMsg.append("<br/>" + successNum + epm.getName() + epm.getIdCard() + " 导入成功");
            } catch (ServiceException e) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum +  epm.getName() + epm.getIdCard() + " 导入失败: " + e.getMessage());
            } catch (Exception e) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum +  epm.getName()+ epm.getIdCard() + " 导入失败: 系统异常"+ e.getMessage());
            }

        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，部分数据导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();




    }


    /**
     * 入职前信息补全
     *
     * @param epmInformation 员工信息主键,修改人
     * @return 结果
     */
//    @Override
    public EpmInformation add_epm_info_Completion(EpmInformation epmInformation){

       //如果部门为空，就分配到一个临时部门去
        if ( epmInformation.getDeptId() == null) {
            epmInformation.setDeptId(200L);
        }
        if(epmInformation.getDate()==null){
            Date currentDate = new Date();
            // 设置当前日期
            epmInformation.setDate(currentDate);
        }

        return epmInformation;
    }



}



